<template>
  <el-dialog class="public-dialog" title="批量操作亚马逊多渠道发货" width="80vw" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <el-card shadow="always" class="w-[100%] mb-[6px]">
      <XForm ref="formRef1" :fieldList="fieldList1" :options="formOptions" :rules="rules" :formData="formData" :originOption="originOption">
        <template #ShipWarehouse>
          <el-select-v2
            v-model="formData.ship_warehouse_id"
            :options="originOption.shipWarehouseOpt"
            :placeholder="'请选择发货仓库'"
            style="width: 280px"
            clearable
            filterable
            @change="shipWarehouseChange"
          />
        </template>
        <template #ShippingMethod>
          <el-select-v2
            v-model="formData.shipping_method_id"
            :options="originOption.shippingMethodOpt"
            placeholder="请选择运输方式"
            style="width: 280px"
            clearable
            filterable
            @change="shippingMethodChange"
            :loading="shippingMethodLoading"
          />
        </template>
      </XForm>
    </el-card>

    <el-card shadow="always" class="w-[100%] mb-[6px]">
      <XForm ref="formRef3" :fieldList="batchFieldList" :options="formOptions" :rules="rules" :formData="formData" :originOption="originOption" />
    </el-card>
    <el-form :model="formData" ref="formRef">
      <el-table :data="formData.items" border class="w-[100%]" max-height="540px" :span-method="objectSpanMethod">
        <el-table-column prop="orderIndex" label="序号" width="55" />
        <el-table-column prop="name" label="平台/站点/店铺" width="160">
          <template #header>
            <div>平台/站点</div>
            <div>店铺</div>
          </template>
          <template #default="{ row }">
            <div>{{ row.platform }} / {{ row.site }}</div>
            <div>{{ row.shop }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="系统订单号/平台订单号" width="180">
          <template #header>
            <div>系统订单号</div>
            <div>平台订单号</div>
          </template>
          <template #default="{ row }">
            <div>{{ row.order_sn }}</div>
            <div>{{ row.platform_order_sn }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="date" label="图片" width="94">
          <template #default="{ row }">
            <el-image :src="row.main_img" class="w-[68px] h-[68px]" style="border: 0.5px solid #f0f0f0; border-radius: 4px">
              <template #error>
                <img src="~@/assets/images/null-img.png" alt="" />
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="系统SKU / 自定义SKU" width="180">
          <template #header>
            <div>系统SKU</div>
            <div>自定义SKU</div>
          </template>
          <template #default="{ row }">
            <div>{{ row.sku }}</div>
            <div>{{ row.custom_sku }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="platform_sku" label="渠道SKU" width="180">
          <template #header>
            <span><span class="text-red text-[16px]">*</span>渠道SKU</span>
            <el-tooltip class="box-item" effect="dark" content="选择的发货店铺对应的渠道SKU" placement="top">
              <div class="dk-iconfont icon-HintFilled"></div>
            </el-tooltip>
            <div>ASIN</div>
          </template>
          <template #default="{ row, $index }">
            <el-form-item :prop="`items.${$index}.platform_sku`" :rules="[{ required: true, message: '请输入', trigger: 'change' }]">
              <el-select v-model="row.platform_sku" placeholder="请选择" filterable class="w-[100%]" @change="platformSkuChange($event, row)">
                <el-option v-for="item in skuOptions[row.id] || []" :key="item.label" :label="item.value" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <div class="pl-[6px]">{{ row.asin }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="sku_cn_title" label="商品名称">
          <template #default="{ row }">
            <VText :value="row.sku_cn_title" :line="3" />
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="available_stock" label="可用库存" width="100">
          <template #header>
            <span>可用库存</span>
            <el-tooltip class="box-item" effect="dark" content="选择的发货店铺对应渠道SKU的可用库存" placement="top">
              <div class="dk-iconfont icon-HintFilled"></div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作" width="90" fixed="right">
          <template #default="{ row, $index }">
            <el-button text type="primary" link @click="resetSku(row)"> 重置 </el-button>
            <el-button text type="danger" link @click="delSku(row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="loading"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { apiGetWarehouseList, feeTrialCalcFreight } from "@/api/public"

import { ElMessage } from "element-plus"
import XForm from "@/components/XForm/index.vue"

import { getEnum } from "@/utils/enumUtils"
onMounted(async () => {})

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex < 3 || columnIndex == 9) {
    if (row.rowIndex == 0) {
      return { rowspan: row.orderLength, colspan: 1 }
    } else {
      return { rowspan: 0, colspan: 0 }
    }
  }
}

// 发货仓库 更改
const shipWarehouseChange = (e) => {
  formData.value.shipping_method_id = null
  if (e) {
    getShippingMethod(e)
    // 获取渠道sku
    formData.value.items.forEach(async (item) => {
      const { data } = await api.query({ goods_sku: [item.sku], warehouse_id: e })
      // 初始化渠道SKU枚举
      if (data.length) {
        skuOptions.value[item.id] = data.map((v) => ({ label: v.seller_sku, value: v.seller_sku, asin: v.asin, available_stock: v["afn-fulfillable-quantity"] }))
      }
    })
  } else {
    originOption.value.shippingMethodOpt = []
    skuOptions.value = {}
    formData.value.items.forEach((item) => {
      item.platform_sku = ""
      item.asin = ""
      item.available_stock = ""
    })
  }
}
// 运输方式 更改
const shippingMethodChange = (e) => {
  formData.value.shipping_method_name = originOption.value.shippingMethodOpt.find((v) => v.value == e)?.label
}
// 获取运输方式
const shippingMethodLoading = ref(false)
const getShippingMethod = (e) => {
  shippingMethodLoading.value = true
  let params = {
    source_os: "oms",
    warehouse: [e],
    customer_order_no: formData.value?.items?.[0].order_sn,
    destination_country: formData.value?.items?.[0].recipient_country,
  }
  feeTrialCalcFreight(params)
    .then((res) => {
      originOption.value.shippingMethodOpt = res.data.map((v) => ({ label: v.channel_name, value: v.channel_id }))
    })
    .finally(() => (shippingMethodLoading.value = false))
}
// 重置sku信息
const resetSku = (row) => {
  formData.value.items.forEach((item) => {
    if (item.order_sn == row.order_sn) {
      item.platform_sku = ""
      item.asin = ""
      item.available_stock = ""
    }
  })
}
// 删除sku信息
const delSku = (row) => {
  formData.value.items = formData.value.items.filter((v) => v.order_sn != row.order_sn)
}

import api from "./api"
const props = defineProps({})
const modelValue = ref(false)
const formData = ref({})

const formOptions = { inline: true, labelWidth: "100px" }
const originOption = ref({
  shipWarehouseOpt: [],
  shippingMethodOpt: [],
})
const publicStyle = { style: { width: "280px" } }
const fieldList1 = [
  { type: "title", label: "发货仓库与运输方式" },
  { field: "ship_warehouse_id", slot: "ShipWarehouse", label: "发货仓库" },
  { field: "shipping_method_id", slot: "ShippingMethod", label: "运输方式" },
]

const batchFieldList = [
  { type: "title", label: "平台信息" },
  { field: "platform_shipping_method_id", label: "配送服务", type: "select", originField: "amazon_shipping_speed_category", options: { placeholder: "配送服务" }, ...publicStyle },
  { field: "order_comment", label: "面单备注", ...publicStyle },
]
const rules = {
  ship_warehouse_id: [{ required: true, message: "请选择", trigger: "change" }],
  shipping_method_id: [{ required: true, message: "请选择", trigger: "change" }],
  platform_shipping_method_id: [{ required: true, message: "请选择", trigger: "change" }],
}

const emit = defineEmits(["refresh", "submit"])

const loading = ref(false)
const formRef = ref()
const formRef1 = ref()
const formRef3 = ref()
const handleSave = async () => {
  loading.value = true
  try {
    await formRef.value.validate()
    await formRef1.value.submit()
    await formRef3.value.submit()
    let keys = ["order_id", "ship_warehouse_id", "shipping_method_id", "shipping_method_name", "order_time", "order_comment", "platform_shipping_method_id"]
    let itemsKey = ["sku", "custom_sku", "platform_sku", "asin", "quantity", "id", "order_item_id", "order_id"]
    let params = {}
    keys.forEach((key) => {
      params[key] = formData.value[key]
    })
    params.items = formData.value.items.map((v) => {
      let row = {}
      itemsKey.forEach((key) => {
        row[key] = v[key]
      })
      return row
    })

    let paramsObj = {}
    params.items.forEach((item) => {
      if (!paramsObj[item.order_id]) paramsObj[item.order_id] = { ...params, order_id: item.order_id, items: [] }
      paramsObj[item.order_id]?.items.push(item)
    })
    paramsObj = Object.values(paramsObj)
    api.saveBatch(paramsObj).then((res) => {
      ElMessage.success("保存成功！")
      handleClose(1)
    })
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
import { getChannelSku } from "@/api/public.js"
const config = ref({
  title: "",
  header: "",
  columns: [],
})

const getBatchOpt = () => {
  let params = {
    wms_platform: ["1"],
    shop_id: [],
  }
  // 若订单所属平台是“亚马逊”，则发货仓库下拉框内容只显示对应订单所属店铺的发货仓库
  if (formData.value.items?.[0].platform_id == 2) {
    params.shop_id = formData.value.items?.[0].shop_id
  }
  apiGetWarehouseList(params).then((res) => {
    originOption.value.shipWarehouseOpt = res.data.map((v) => ({ label: v.warehouse_name, value: v.id, shop_id: v.shop_id }))
  })
}
// 渠道sku变动
const platformSkuChange = (e, row) => {
  let item = skuOptions.value[row.id].find((v) => v.value == e)
  row.asin = item?.asin
  row.available_stock = item.available_stock
}

const skuOptions = ref({})

const tableData = ref([])
const open = async (row) => {
  let optData = await getEnum(["amazon_shipping_speed_category"])
  originOption.value.amazon_shipping_speed_category = optData.amazon_shipping_speed_category
  modelValue.value = true

  // 批量
  formData.value.platform_shipping_method_id = 3
  let items = row.map((v, idx) => {
    v.items = v.items.map((x, i) => ({
      ...x,
      platform: v.platform,
      site: v.site,
      shop: v.shop,
      order_sn: v.order_sn,
      platform_order_sn: v.platform_order_sn,

      // 自定义参数
      order_id: v.id,
      shop_id: v.shop_id,
      platform_id: v.platform_id,
      recipient_country: v.recipient.recipient_country,
      orderLength: v.items.length,
      rowIndex: i,
      orderIndex: idx + 1,
    }))

    return v.items
  })
  items = items.flat()
  items = items.map((v) => ({ ...v, platform_sku: "", asin: "" }))

  formData.value.items = items
  getBatchOpt()
  formData.value.order_comment = "Thank you for your order !"
}
const handleClose = (refresh) => {
  modelValue.value = false
  formData.value = {}
  skuOptions.value = {}
  originOption.value.shippingMethodOpt = []
  if (refresh == 1) emit("refresh")
}

defineExpose({
  open,
})
</script>
<style lang="scss" scoped>
:deep(.el-card__body) {
  padding-top: 10px;
  padding-bottom: 0;
}
</style>
